package com.example.computer_exam_training_sys.ultils;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class AvatarUploadUtil {
    // 保存头像，返回文件名
    public String saveAvatar(MultipartFile file, String uploadDir) throws IOException {
        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename != null && originalFilename.contains(".") ? originalFilename.substring(originalFilename.lastIndexOf('.')) : "";
        // 用当前时间戳+3位随机数做编号
        String newFileName = System.currentTimeMillis() + String.valueOf((int)(Math.random()*900+100)) + ext;
        // 绝对路径（始终用前端public/avatars目录）
        File dir = new File("E:/project/front_project/front_Computer_exam_training_Sys/public/avatars");
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                throw new IOException("头像目录创建失败: " + dir.getAbsolutePath());
            }
        }
        // 保存文件
        File dest = new File(dir, newFileName);
        file.transferTo(dest);
        // 只返回文件名
        return newFileName;
    }
}
